import router from "./router";
import { getRefreshToken, getToken } from "@/utils/auth";
import { to as tos } from "await-to-js";
import { isReLogin } from "@/utils/request";
import { isHttp } from "@/utils/validate";
import usePermissionStore from "@/store/modules/permission";
import useUserStore from "@/store/modules/user";
import useSettingsStore from "@/store/modules/settings";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css";

//全局进度条的配置
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
});

/** 白名单 */
const whiteList = ["/login"];

/**
 * 路由守卫
 */
router.beforeEach(async (to, _from, next) => {
  NProgress.start();
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (useUserStore().roles.length === 0) {
        isReLogin.show = true;
        const [err] = await tos(useUserStore().getInfo());
        if (err) {
          // 退出登陆
          const refreshToken = getRefreshToken();
          await useUserStore().logout(refreshToken);
          next({ path: "/" });
        } else {
          isReLogin.show = false;
          // 获取动态路由
          const accessRoutes = await usePermissionStore().generateRoutes();
          // 根据roles权限生成可访问的路由表
          accessRoutes.forEach(route => {
            if (!isHttp(route.path)) {
              // 动态添加可访问的路由
              router.addRoute(route);
            }
          });
          next({ ...to, replace: true });
        }
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
